<!--
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-04-17 13:33:51
 * @Description  : 重命名组件
-->
<template>
  <div
    @click="handleOnClick"
    class="show-or-edit-con cursor-text"
    @mousedown="handleDragStart"
  >
    <n-input
      v-if="props.isEdit"
      ref="inputRef"
      :value="inputValue"
      @update:value="handleValueChange"
      @blur="handleBlur"
      @change="handleChange"
      @keydown="handleKeyDown"
    ></n-input>
    <n-ellipsis
      class="text-center"
      v-else
      :line-clamp="2"
      style="max-width: 100px"
    >
      <span v-html="myHtml"></span>

      <template #tooltip>
        <div style="text-align: center">
          {{ value }}
        </div>
      </template>
    </n-ellipsis>
  </div>
</template>

<script setup lang="ts">
const props = defineProps<{
  value: string | number
  isEdit: boolean
}>()

const myHtml = computed(() => {
  const value = props.value
  if (typeof value === 'string') {
    if (value.length > 15) {
      return (
        value.substring(0, 7) +
        '<br />' +
        value.substring(7, 14) +
        '<br />' +
        value.substring(14)
      )
    } else {
      return value
    }
  }
  return value
})

const emits = defineEmits<{
  (e: 'edit-change', value: boolean): void
  (e: 'update:value', value: string | number): void
  (e: 'on-finish', value: string | number): void
}>()

watch(
  () => props.isEdit,
  (newValue) => {
    if (newValue) {
      nextTick(() => {
        inputRef.value!.focus()
        // inputRef.value!.select()
      })
    }
  },
  {
    immediate: true
  }
)

const inputRef = ref()
const inputValue = ref(props.value)
const initValue = ref(props.value)
const handleOnClick = (e: MouseEvent) => {
  e.stopPropagation()
  emits('edit-change', true)
  if (props.isEdit) {
    nextTick(() => {
      inputRef.value!.focus()
      // inputRef.value!.blur()
    })
  }
}

const handleValueChange = (v: string | number) => {
  inputValue.value = v
}

const handleDragStart = (e: MouseEvent) => {
  e.preventDefault()
  e.stopPropagation()
}

const handleBlur = () => {
  emits('update:value', inputValue.value)
  emits('edit-change', false)
  emits('on-finish', initValue.value)
}

const handleChange = () => {
  emits('update:value', inputValue.value)
  emits('edit-change', false)
}

const handleKeyDown = (e: KeyboardEvent) => {
  console.log(e.key)

  if (e.key === 'Enter') {
    handleChange()
  }
}
</script>

<style scoped lang="scss"></style>
